package zhtt;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import java.io.File;
import java.util.Properties;

/**
 * Created by zhtt on 2017/4/10.
 */
public class ConfigureTest {

    public static void main(String[] args){
        test03();
    }
    public static void test01(){
        //为Configuration指定映射文件
        Configuration cfg = new Configuration().addResource("zhtt/student.hbm.xml");
        //为Configuration指定持久化类
        cfg.addClass(zhtt.Student.class);
        //为Configuration指定配置属性
        cfg.setProperty("hibernate.dialect","org.hibernate.dialect.MySQLInnoDBDialect")
//                .setProperty("hibernate.connection.datasource","java:comp/env/jdbc/test")//jndi
                .setProperty("hibernate.order_update","true")
                .setProperty("hibernate.connection.driver_class","com.mysql.jdbc.Driver")
                .setProperty("hibernate.connection.url","jdbc:mysql://localhost:3306/test?createDatabaseIfNotExist=true&amp;useUncode=true&amp;characterEncoding=UTF-8")
                .setProperty("hibernate.connection.username","root")
//                .setProperty("hibernate.connection.password","")
                .setProperty("current_session_context_class","thread");
        SessionFactory sessionFactory=cfg.buildSessionFactory();
        get(sessionFactory);
    }

    public static void test02(){
        //为Configuration指定映射文件
        Configuration cfg = new Configuration().addResource("zhtt/student.hbm.xml");
        //为Configuration指定持久化类
        cfg.addClass(zhtt.Student.class);
        Properties properties = null;
        cfg.setProperties(properties);
        SessionFactory sessionFactory=cfg.buildSessionFactory();
        get(sessionFactory);
    }

    public static void test03(){
        //为Configuration指定映射文件
        Configuration cfg = new Configuration().addResource("zhtt/student.hbm.xml").setProperties(PropertiesUtil.get());
        //为Configuration指定持久化类
        cfg.addClass(zhtt.Student.class);
        SessionFactory sessionFactory=cfg.buildSessionFactory();
        get(sessionFactory);
    }

    private static void get(SessionFactory sessionFactory){
        Session session=sessionFactory.openSession();
        try{
            session.beginTransaction();
            Student student=session.get(Student.class,1);
            System.out.println(student);
            session.getTransaction().commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            session.close();
            sessionFactory.close();
        }
    }
}
